from django.contrib import admin

# Register your models here.
from django.urls import reverse
from django.utils.html import format_html

from .models import Category, Tag, Post
from .adminforms import PostAdminForm


class PostInline(admin.TabularInline):  # StackedInline样式不同
    """ 在同一界面编辑关联数据,可以在编辑分类的时候增加文章 """
    fields = ('title', 'desc')
    extra = 1  # 额外多控制几个
    model = Post


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    inlines = [PostInline, ]
    list_display = ('name', 'status', 'is_nav', 'owner', 'created_time')  # 配置列表展示界面
    # fields = ('name', 'status', 'is_nav')  # 控制页面上要展示的字段

    def save_model(self, request, obj, form, change):  # 保存数据到数据库中
        obj.owner = request.user
        return super(CategoryAdmin, self).save_model(request, obj, form, change)

    fieldsets = (
        ('基础配置', {
            'description': '基础分类配置',
            'fields': (
                'name',
                'status'
            )
        }),
        ('其他', {
            'classes': ('collapse',),
            'fields': ('is_nav',),
        })
    )  # 控制增加或修改页面布局


@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    list_display = ('name', 'status', 'created_time')  # 配置列表展示界面
    fields = ('name', 'status')  # 控制页面上要展示的字段

    def save_model(self, request, obj, form, change):  # 保存数据到数据库中
        obj.owner = request.user
        return super(TagAdmin, self).save_model(request, obj, form, change)


class CategoryOwnerFilter(admin.SimpleListFilter):

    """ 自定义过滤器只展示当前用户分类 """

    title = '分类过滤器'
    parameter_name = 'owner_category'

    def lookups(self, request, model_admin):  # 返回要展示的内容和查询用的id
        return Category.objects.filter(owner=request.user).values_list('id', 'name')

    def queryset(self, request, queryset):  # 根据URL Query的内容返回列表页数据
        category_id = self.value()
        if category_id:
            return queryset.filter(category_id=category_id)
        return queryset


@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    form = PostAdminForm
    list_display = [
        'title', 'category', 'status',
        'created_time', 'owner', 'operator'
    ]  # 配置列表展示界面
    exclude = ['owner', ]
    list_display_links = []  # 配置哪些字段可以作为链接，点击可以编辑界面
    list_filter = [CategoryOwnerFilter, ]  # 配置页面过滤器，可以通过列表中的值对数据进行过滤
    search_fields = ['title', 'category__name']  # 配置搜索字段

    actions_on_top = True  # 动作相关配置，是否展示在顶部
    actions_on_bottom = True  # 动作相关配置，是否展示在底部

    save_on_top = False  # 保存、编辑、编辑并新建按钮是否在顶部展示

    # fields = (
    #     ('category', 'title'),
    #     'desc',
    #     'status',
    #     'content',
    #     'tag',
    # )  # 控制页面上展示的字段

    fieldsets = (
        ('基础配置', {
            'description': '基础配置描述',
            'fields': (
                ('title', 'category'),
                'status'
            )
        }),
        ('内容', {
            'fields': (
                'desc',
                'content',
            ),
        }),
        ('额外信息', {
            'classes': ('collapse', ),
            'fields': ('tag', ),
        })
    )  # 控制增加或修改页面布局

    def operator(self, obj):
        return format_html(
            '<a href="{}">编辑</a>',
            reverse('admin:blog_post_change', args=(obj.id, ))
        )
    operator.short_description = '操作'

    def save_model(self, request, obj, form, change):
        obj.owner = request.user
        return super(PostAdmin, self).save_model(request, obj, form, change)

    def get_queryset(self, request):  # 只显示当前登录用户文章
        qs = super(PostAdmin, self).get_queryset(request)
        return qs.filter(owner=request.user)

    class Media:

        css = {
            'all': ("https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css", ),
        }
        js = ("https://cdn.bootstrap.com/bootstrap/4.0.0-beta.2/js/bootstrap.bundle.js", )


